/**
 * @Description: vue config文件
 * @Author: jiangang
 * @Date: 2022-03-07
 * @LastEditTime: 10:22:05
 */
import axios from 'axios';
import {setStorage} from '@/utils/storage';
import Vue from 'vue'

const isDev = process.env.NODE_ENV !== 'production'
const produceUrl = '/admin'
const devUrl = 'http://48.30.2.160:3000/api'
// 生产环境地址
const apiBase = isDev ? devUrl : produceUrl
// http状态码
const httpStatusMap = new Map([
  [404, '访问的地址不存在'],
  [500, '服务器错误']
])
const cancelList = []

const needHeaderUrl = ['/evaluate/exportTask', '/evaluate/exportTaskByTaskId', '/evaluate/exportReport']
const responseResolve = (res) => {
  res.cancelToken = new axios.CancelToken(function exector(c) {
    cancelList.push(c)
  })
  const {token} = res.headers
  if (token) {
    setStorage('token', token)
  }
  if (needHeaderUrl.includes(res.config.url.split('?')[0])) {
    return Promise.resolve(res);
  }
  const { data: json = {} } = res;
  const { code, msg, data = {} } = json;
  switch (code) {
    case 0: {
      return Promise.resolve(data);
    }
    case 200: {
      return Promise.resolve(data);
    }
    default: {
      if (code === 400) {
        cancelList.forEach(cancel => {
          cancel()
        })
      }
      const { pathname, search, origin } = window.location
      if (code === 401 && pathname !== '/login') {
        Vue.prototype.$alert('用户身份失效，请重新登录！').then(() => {
          window.location.href = `${origin}/login?redirect_uri=${encodeURIComponent(`${pathname}${search}`)}`
        })
      }
      const responseError = {
        serverErrorCode: code,
        ...json,
        msg
      };
      return Promise.reject(responseError);
    }
  }
};
const defaultServerErrorPrefix = '连接出错';

const responseError = (err) => {
  const code = err && err.response ? (err.response.code || err.response.serverErrorCode) : 999;
  const message = err.msg || httpStatusMap.get(code) || `${defaultServerErrorPrefix}(${code})`;
  return Promise.reject(new Error(message));
};

export {
  responseResolve,
  responseError,
  apiBase
};
